//
//  ZXAFManager.m
//  ClassManager
//
//  Created by mac on 2018/4/17.
//  Copyright © 2018年 GZX. All rights reserved.
//

#import "ZXAFManager.h"

static ZXAFManager *manager = nil;

@implementation ZXAFManager



#pragma mark - 单例get
-(void)GET:(NSString *)URLString parameters:(id)parameters success:(void (^)(id responseObject))success{
    NSString *url = [self.mainURL stringByAppendingString:URLString];
    if ([parameters count] > 0)
        NSLog(@"%@&%@", url, [ZXAFManager appendParameters:parameters]);
    else
        NSLog(@"%@",url);

    [self.session GET:url parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            NSLog(@"请求成功：\n%@",responseObject);
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求失败---------%@",error);
    }];
}
#pragma mark - 单例post
-(void)POST:(NSString *)URLString parameters:(id)parameters success:(void (^)(id responseObject))success{

    NSString *url = [self.mainURL stringByAppendingString:URLString];
    if ([parameters count] > 0)
        NSLog(@"%@&%@", url, [ZXAFManager appendParameters:parameters]);
    else
        NSLog(@"%@",url);

    [self.session POST:url parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            NSLog(@"请求成功：\n%@",responseObject);
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求失败---------%@",error);
    }];
}


-(instancetype)init{
    self = [super init];
    if (self) {
        self.session = [AFHTTPSessionManager manager];
        self.session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/xml", @"text/plain", nil];
        self.session.requestSerializer.timeoutInterval = 30.;
        self.mainURL = @"https://baidu.com";
    }
    return self;
}
-(void)resquestCancel{
    [self.session invalidateSessionCancelingTasks:YES];
}
#pragma mark - 拼接请求链接
+(NSString *)appendParameters:(id)parameters{
    NSDictionary *dict = (NSDictionary *)parameters;
    NSArray *allKeys = dict.allKeys;
    NSString *string = @"";
    for (NSString *key in allKeys) {
        string = [string stringByAppendingFormat:@"%@%@=%@", string.length==0?@"":@"&", key,dict[key]];
    }
    return string;
}
+(ZXAFManager *)shareClient{
    static dispatch_once_t onceToken ;
    dispatch_once(&onceToken, ^{
        manager = [[super allocWithZone:NULL] init];
    }) ;
    return manager;
}

+(id) allocWithZone:(struct _NSZone *)zone{
    return [ZXAFManager shareClient] ;
}

-(id) copyWithZone:(struct _NSZone *)zone{
    return [ZXAFManager shareClient] ;
}

@end
